package com.ixoko.swagger.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author luojie
 * @Date 2018/7/1
 */
public class HttpClientUtil {

    public static String TOKEN = "";


    public static String post(String url, String body) throws IOException, ExecutionException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //解决中文乱码问题
        StringEntity entity = new StringEntity(body, "utf-8");

        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.addHeader("token", TOKEN);
        httpPost.setEntity(entity);

        HttpResponse resp = httpClient.execute(httpPost);
        return EntityUtils.toString(resp.getEntity());
    }

    public static String get(String url, HashMap<String, String> param) throws IOException, ExecutionException, URISyntaxException {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        //解决中文乱码问题
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, String> stringStringEntry : param.entrySet()) {
            builder.setParameter(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
        HttpGet httpGet = new HttpGet(builder.build());
        httpGet.addHeader("token", TOKEN);

        HttpResponse resp = httpClient.execute(httpGet);
        return EntityUtils.toString(resp.getEntity());
    }


    public static String post(String url, String body, HashMap<String, String> headerMap) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //解决中文乱码问题
        StringEntity entity = new StringEntity(body, "utf-8");

        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        if (headerMap != null && !headerMap.isEmpty()) {
            headerMap.entrySet().forEach(e -> {
                httpPost.addHeader(e.getKey(), e.getValue());
            });
        }
        httpPost.setEntity(entity);

        HttpResponse resp = httpClient.execute(httpPost);
        return EntityUtils.toString(resp.getEntity());
    }

}
